/*
 * @Author: fanjs
 * @Date: 2025-04-09 18:11:03
 * @Description: 邮件内容
 */
import { useState, useRef, useCallback } from 'react';
import { Input, Button, addToast, useDisclosure, Card, CardHeader, CardBody, CardFooter, Tooltip, Popover, PopoverTrigger, PopoverContent } from "@heroui/react";
import { createTaskApi, createTemplateApi, updateTemplateApi, updateTaskApi } from '@/service/api/email'
import Editor from './components/Editor'
import TemplateDrawer from './components/TemplateDrawer'
import TaskDrawer from './components/TaskDrawer'
import { SvgIcon } from '@/components/SvgIcon'
import { useNavigate } from 'react-router-dom'

const EmailContent: React.FC = () => {
  const navigate = useNavigate()

  const editorRef = useRef<any>(null)

  const { isOpen, onOpen, onOpenChange } = useDisclosure();
  const [template_id, setTemplateId] = useState('') // 模板ID

  const { isOpen: isTaskOpen, onOpen: onTaskOpen, onOpenChange: onTaskOpenChange } = useDisclosure();
  const [task_id, setTaskId] = useState('') // 任务ID
  const [taskInfo, setTaskInfo] = useState<any>({}) // 任务信息

  const [subject, setSubject] = useState('') // 邮件主题
  const [content, setContent] = useState('') // 邮件内容
  const [variables, setVariables] = useState<string[]>([]) // 变量

  // 添加变量
  const [isVariableOpen, setIsVariableOpen] = useState(false);
  const [variableName, setVariableName] = useState('') // 变量名称
  const addVariable = () => {
    if (!variableName) return addToast({ title: "请输入变量名称" })
    setVariables([...variables, variableName])
    setVariableName('')
    setIsVariableOpen(false)
  }
  // 删除变量
  const removeVariable = (index: number) => {
    setVariables(variables.filter((_, i) => i !== index))
  }

  // 处理编辑器内容变化
  const handleEditorChange = useCallback((html: string) => {
    setContent(html)
  }, []);

  // 选择模板 （调用 api 操作模板时，不打开弹窗）
  const selectTemplate = (template?: any, isApi?: boolean) => {
    if (template) {
      setTemplateId(template.id) // 设置模板id
      setVariables(template.variables) // 设置变量
      setContent(template.content) // 设置邮件内容
      setSubject(template.subject) // 设置邮件主题
    }
    if (!isApi) onOpenChange()
  }

  // 选择任务
  const selectTask = (task?: any) => {
    if (task) {
      setTaskId(task.id) // 设置任务id
      setTaskInfo(task) // 设置任务信息
      // 设置邮件内容
      setContent(task.content)
      setSubject(task.subject)
      setVariables(task.variables)
      // 清空模板id
      setTemplateId('')
    }
    onTaskOpenChange()
  }

  // 校验文本内容中是否包含了全部的变量值
  const checkVariables = () => {
    return new Promise((resolve) => {
      const varArray = variables.map(item => `{{${item}}}`)
      resolve(varArray.every(item => content.includes(item)))
    })
  }

  // 校验提交信息
  const checkSubmit = async () => {
    if (!subject) {
      addToast({ title: "请输入邮件主题" })
      return false
    }
    if (!content) {
      addToast({ title: "请输入邮件内容" })
      return false
    }
    if (!variables.length) {
      addToast({ title: "请设置变量名称" })
      return false
    }
    const result = await checkVariables()
    if (!result) {
      addToast({ title: "请在邮件内容中加入全部变量" })
      return false
    }
    return true
  }
  // 保存模板
  const saveTemplate = async (action: string) => {
    const passed = await checkSubmit()
    if (!passed) return

    try {
      const apiMap: { [key: string]: any } = {
        'create': createTemplateApi,
        'update': updateTemplateApi
      }
      const params: any = { subject, content, variables }
      if (action === 'update') params.id = template_id
      const { data } = await apiMap[action](params)
      if (data) {
        addToast({ title: action === 'update' ? "更新成功" : "保存成功", color: 'secondary' })
        selectTemplate(data, true)
      }
    } catch (error) {
      console.error(error)
    }
  }

  /**
   * 根据 模板信息 生成任务
   * @param {string} subject - 邮件主题
   * @param {string} content - 邮件内容
   * @param {string[]} variables - 变量
   * @returns {Promise<any>} - 返回任务ID
   **/
  const generateTask = async () => {
    try {
      const params: any = { subject, content, variables }
      const { data }: any = await createTaskApi(params)
      return Promise.resolve(data)
    } catch (error) {
      return Promise.reject(error)
    }
  }


  // 去配置收件人
  const toRecipients = async () => {
    try {
      const passed = await checkSubmit()
      if (!passed) return

      // 如果选择了任务，则跳转到收件人配置页面
      if (task_id) {
        // 更新任务信息
        const updateData: any = {}
        if (taskInfo.subject !== subject) updateData.subject = subject
        if (taskInfo.content !== content) updateData.content = content
        if (taskInfo.variables !== variables) updateData.variables = variables
        if (Object.keys(updateData).length) {
          const { data } = await updateTaskApi({ task_id, ...updateData })
          if (data) addToast({ title: "更新任务信息成功" })
        }

        // 跳转
        navigate(`/distribute/recipients/${task_id}`)
        return
      }

      // 生成任务
      const task = await generateTask()
      if (task && task.id) {
        navigate(`/distribute/recipients/${task.id}`)
      } else {
        addToast({ title: "生成任务失败了，请刷新重试" })
      }
    } catch (error) {
      console.error(error)
    }
  }

  return (
    <div className="flex-center py-3 px-3">
      <Card className="h-[calc(100vh-82px)] !max-w-[1200px]">
        <CardHeader className="font-semibold">
          <h3 className="text-md flex-y-center">
            <SvgIcon icon="line-md:email" className='text-xl mr-1' />
            配置邮件内容
          </h3>
        </CardHeader>
        <CardBody className="flex flex-col gap-4">
          <Input
            isRequired
            value={subject}
            onValueChange={setSubject}
            label="邮件主题"
          />

          <div className="flex gap-3">
            <Tooltip content={
              <div className="px-1 py-2">
                <div className="text-small font-bold">变量：在邮件内容中会变化的值（需要被替换的文本）</div>
                <div className="text-tiny mt-2">1. 首先创建变量名，建议变量名与文档中表格的列头文本一致</div>
                <div className="text-tiny mt-2">2. 将变量插入在邮件内容中需要被替换的文本处</div>
                <div className="text-tiny mt-2">3. 确保所有变量在邮件内容中都被使用，或者删除未使用的变量</div>
              </div>
            } placement="bottom">
              <div className="flex-y-center h-8">
                <SvgIcon icon="line-md:question-circle" className='text-lg mr-1' />
                设置变量：
              </div>
            </Tooltip>
            {variables.map((item: any, index: number) => (
              <div className='flex-y-center h-8'>
                <Button
                  color="secondary"
                  variant="flat"
                  size="sm"
                  className='h-8 cursor-pointer rounded-[4px] gap-0 font-bold'
                  onPress={() => {
                    const text = `{{${item}}}`
                    const textArea = document.createElement('textarea')
                    textArea.value = text
                    document.body.appendChild(textArea)
                    textArea.select()
                    try {
                      document.execCommand('copy')
                      addToast({ title: "复制成功" })
                    } catch (error: any) {
                      console.error(error)
                      addToast({ title: "复制失败，请手动复制" })
                    }
                    document.body.removeChild(textArea)
                  }}
                >
                  <span className='font-bold pl-1'>{`{{${item}}}`}</span>
                  <SvgIcon icon="mdi:content-copy" className='text-[14px] ml-2' />
                </Button>
                <div className='cursor-pointer text-danger pl-1' onClick={() => removeVariable(index)}>
                  <SvgIcon icon="line-md:close" className='text-[14px]' />
                </div>
              </div>
            ))}

            <Popover showArrow backdrop="opaque" isOpen={isVariableOpen} onOpenChange={setIsVariableOpen} offset={10} placement="bottom">
              <PopoverTrigger>
                <Button color="secondary" variant="bordered" size="sm" className='border-dashed border-1 rounded-[4px]'>
                  添加
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[240px] p-0">
                <Input endContent={
                  <Button color="secondary" variant="flat" isIconOnly size="sm" onPress={addVariable} className='cursor-pointer rounded-[4px] flex-y-center'>
                    <SvgIcon icon="line-md:check-all" className='text-lg' />
                  </Button>
                } value={variableName} onValueChange={setVariableName} placeholder='输入变量名称' size="md" />
              </PopoverContent>
            </Popover>

          </div>

          <Editor ref={editorRef} content={content} onChange={handleEditorChange} />
        </CardBody>
        <CardFooter className="gap-3 flex-center">
          <Button color="secondary" variant="flat" onPress={() => onTaskOpen()}>历史任务</Button>
          <Button color="secondary" variant="flat" onPress={() => onOpen()}>选择模板</Button>
          {template_id
            ?
            <>
              <Button color="secondary" variant="flat" isDisabled={!subject || !content} onPress={() => saveTemplate('update')}>更新模板</Button>
              <Button color="secondary" variant="flat" isDisabled={!subject || !content} onPress={() => saveTemplate('create')}>存为新模板</Button>
            </>
            :
            <Button color="secondary" isDisabled={!subject || !content} onPress={() => saveTemplate('create')}>保存模板</Button>
          }
          <Button color="secondary" isDisabled={!subject || !content} onPress={toRecipients}>配置收件人</Button>
        </CardFooter>
      </Card>
      <TemplateDrawer isOpen={isOpen} template_id={template_id} submit={selectTemplate} />
      <TaskDrawer isOpen={isTaskOpen} task_id={task_id} submit={selectTask} />
    </div>
  )
};

export default EmailContent;
